package com.example.gulimallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.utils.R;
import com.example.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.example.gulimallproduct.entity.AttrGroupEntity;
import com.example.gulimallproduct.entity.CategoryEntity;
import com.example.gulimallproduct.request.SaveAttrRequest;
import com.example.gulimallproduct.request.UpdateAttrRequest;
import com.example.gulimallproduct.response.SelectAttrInfoResponse;
import com.example.gulimallproduct.response.selectAttrPageResponse;
import com.example.gulimallproduct.service.*;
import com.example.gulimallproduct.utlis.SetCatelogPathUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallproduct.dao.AttrDao;
import com.example.gulimallproduct.entity.AttrEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private CategoryService categoryService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    public R selectPageWhthBase(Map<String, Object> params, Long catId, Integer type) {
        // 安全地获取 key 参数
        Object keyObj = params.get("key");
        String keyValue = keyObj != null ? keyObj.toString() : null;

        IPage<AttrEntity> page = page(
                new Query<AttrEntity>().getPage(params),
                new LambdaQueryWrapper<AttrEntity>()
                        .eq(catId!=0, AttrEntity::getCatelogId, catId)
                        .likeRight(StringUtils.isNotBlank(keyValue), AttrEntity::getAttrName, keyValue)
                        .eq(AttrEntity::getAttrType, type)
                        .eq(AttrEntity::getEnable, 1)
        );
        PageUtils pageUtils = new PageUtils(page);
        List<selectAttrPageResponse> list = page.getRecords().stream().map(item -> {
            selectAttrPageResponse response = new selectAttrPageResponse();
            BeanUtils.copyProperties(item, response);
            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if(Objects.nonNull(categoryEntity)){
                response.setCatelogName(categoryEntity.getName());
            }
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, item.getAttrId()).one();
            if (Objects.nonNull(attrAttrgroupRelationEntity)&&Objects.nonNull(attrAttrgroupRelationEntity.getAttrGroupId())){
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                if(Objects.nonNull(attrGroupEntity)){
                    response.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return response;
        }).toList();
        pageUtils.setList(list);
        return R.ok().put("page", pageUtils);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveAttr(SaveAttrRequest attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        save(entity);
        if(Objects.nonNull(attr.getAttrGroupId())){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(entity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

        return R.ok();
    }

    @Override
    public R selectInfoById(Long attrId) {
        SelectAttrInfoResponse response = new SelectAttrInfoResponse();
        AttrEntity attrEntity = getById(attrId);
        BeanUtils.copyProperties(attrEntity, response);
        // 获取分组信息
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attrId).one();
        if(Objects.nonNull(attrAttrgroupRelationEntity)){
            response.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
            if(Objects.nonNull(attrGroupEntity)){
                response.setAttrGroupName(attrGroupEntity.getAttrGroupName());
            }
        }
         // 获取分类路径
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        if(Objects.nonNull(categoryEntity)){
            response.setCatelogPath(SetCatelogPathUtils.getCatelogPath(categoryEntity, categoryService));
        }
        return R.ok().put("attr", response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateAttr(UpdateAttrRequest attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        updateById(entity);
        // 更新分组信息
        if(Objects.nonNull(attr.getAttrGroupId())){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()).one();
            if(Objects.nonNull(attrAttrgroupRelationEntity)){
                attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.updateById(attrAttrgroupRelationEntity);
            }else{
                AttrAttrgroupRelationEntity newAttrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
                newAttrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
                newAttrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
                attrAttrgroupRelationService.save(newAttrAttrgroupRelationEntity);
            }
        }
        return R.ok();
    }

}